package com.killer.utils;

import jdk.jshell.spi.ExecutionControl;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class PackageSacnUtil {

    public static List<String> listAllClass(String packageName) {
        String path = getPackagePath(packageName);
        return listAllClass(path, packageName);

    }

    private static List<String> listAllClass(String path, String packageName) {
        List<String> classNames=new ArrayList<String>();
        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException("文件:" + path + "找不到");
        }
        //判断是不是目录
        if (file.isDirectory()) {
            //是目录则遍历下面的所有文件
            File[] childFiles = file.listFiles();
            if (childFiles != null) {
                for (File childFile : childFiles) {
                    classNames.addAll(listAllClass(childFile.getPath(),packageName+"."+childFile.getName()));
                }
            }

        }else{
            //不是目录的话打印文件名
            if (file.getName().endsWith(".class")) {
                classNames.add(packageName.substring(0, packageName.lastIndexOf(".")));
            }
        }
        return classNames;
    }

    /**
     * 获取某个包在工程下的路径
     * @param packageName
     * @return
     */
    private static String getPackagePath(String packageName) {
        try {
            Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(packageName.replace(".", "/"));
            while (urls.hasMoreElements()) {
                return URLDecoder.decode(urls.nextElement().getPath(), "UTF-8");
            }
        } catch (IOException e) {
            throw new RuntimeException("包路径:" + packageName + "找不到");
        }
        return null;
    }
}
